using OneAuthCenter.Client.Extensions;

var builder = WebApplication.CreateBuilder(args);

// ============================================================
// 🔐 集成 OneAuthCenter 认证（3 种方式任选其一）
// ============================================================

// 方式 1：代码配置（推荐用于开发环境）
builder.Services.AddOneAuthCenter(options =>
{
    options.Authority = builder.Configuration["OneAuthCenter:Authority"] 
        ?? "https://localhost:5001";
    options.Audience = "orders-api";
    options.RequireHttpsMetadata = false;  // 开发环境设置为 false
});

// 方式 2：从配置文件读取（推荐用于生产环境）
// builder.Services.AddOneAuthCenter(builder.Configuration);

// 方式 3：带 Scope 验证
// builder.Services.AddOneAuthCenter(
//     authority: "https://localhost:5001",
//     audience: "orders-api",
//     requiredScopes: "orders.read", "orders.create"
// );

// ============================================================
// 🛡️ 配置授权策略
// ============================================================
builder.Services.AddAuthorization(options =>
{
    // 读取订单策略
    options.AddPolicy("OrdersRead", policy =>
        policy.RequireClaim("scope", "orders.read"));
    
    // 创建订单策略
    options.AddPolicy("OrdersCreate", policy =>
        policy.RequireClaim("scope", "orders.create"));
    
    // 删除订单策略（需要管理员角色）
    options.AddPolicy("OrdersDelete", policy =>
    {
        policy.RequireClaim("scope", "orders.delete");
        policy.RequireClaim("role", "Admin");
    });
});

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "订单 API - OneAuthCenter 集成示例", Version = "v1" });
    
    // 配置 Swagger 的 JWT Bearer 认证
    c.AddSecurityDefinition("Bearer", new()
    {
        Name = "Authorization",
        Type = Microsoft.OpenApi.Models.SecuritySchemeType.Http,
        Scheme = "Bearer",
        BearerFormat = "JWT",
        In = Microsoft.OpenApi.Models.ParameterLocation.Header,
        Description = "请输入从 OneAuthCenter 获取的 JWT Token"
    });
    
    c.AddSecurityRequirement(new()
    {
        {
            new()
            {
                Reference = new()
                {
                    Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            Array.Empty<string>()
        }
    });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

// ⚠️ 顺序很重要！
app.UseAuthentication();  // 必须在 UseAuthorization 之前
app.UseAuthorization();

app.MapControllers();

Console.WriteLine("=".PadRight(60, '='));
Console.WriteLine("🎯 订单 API 已启动");
Console.WriteLine("📖 Swagger UI: https://localhost:7001/swagger");
Console.WriteLine("🔐 认证方式: OneAuthCenter JWT Bearer");
Console.WriteLine("=".PadRight(60, '='));

app.Run();

